package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Card;
import com.gaohe.pojo.User;
import com.gaohe.pojo.UserCard;
import com.gaohe.service.CardService;
import com.gaohe.service.UserCardService;
import com.gaohe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/card")
@Slf4j
public class CardController {
    @Autowired
    private UserService userService;
    @Autowired
    private CardService cardService;
    @Autowired
    private UserCardService userCardService;
    @GetMapping("/page")
    public R page(@RequestParam int page,
                  @RequestParam int pageSize,
                  @RequestParam(required = false) String name){
        //分页条件
        Page<Card> cardPage = new Page<>(page, pageSize);
        //查询条件
        LambdaQueryWrapper<Card> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Card::getName,name);
        qw.orderByDesc(Card::getUpdateTime);
        //分页查询
        cardService.page(cardPage,qw);
        return R.success(cardPage);
    }
    //会员卡禁用
    @PutMapping
    public R cardStatus(@RequestBody Card card){
        boolean b = cardService.updateById(card);
        return b?R.success("修改成功"):R.error("修改失败");
    }
    //会员卡删除
    @DeleteMapping
    public R deleteCard(@RequestParam Long id){
        boolean b = cardService.removeById(id);
        return b?R.success("删除成功"):R.error("删除失败");
    }
    //新增会员卡
    @PostMapping
    public R insert(@RequestBody Card card)
    {
        boolean b = cardService.save(card);
        return b?R.success("新增成功"):R.error("新增失败");
    }
    //会员卡修改回显
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){
        return R.success(cardService.getById(id));
    }
    //查询拥有该卡的用户
    @GetMapping("/user/{id}")
    public R findByCardtoUser(@PathVariable Long id){
        List<User> byCardtoUser = cardService.findByCardtoUser(id);
        return R.success(byCardtoUser);
    }
    @GetMapping("/getCardList")
    public R getCardList(@RequestParam(required = false) String type){
        LambdaQueryWrapper<Card> qw = new LambdaQueryWrapper<>();
        qw.eq(!StringUtils.isEmpty(type),Card::getType,type);
        qw.orderByDesc(Card::getUpdateTime);
        return R.success(cardService.list(qw));
    }




    }
